from functools import wraps
from flask import Flask, render_template, session, redirect, url_for, request, jsonify, abort, flash, g
from mysql_util import MysqlUtil
import bcrypt

app = Flask(__name__)
app.config['SECRET_KEY'] = 'ywiasjooasywwsasaswasww'

##########装饰器

# def login_required(func):
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         if 'username' not in session:
#             return redirect(url_for('login'))
#         return func(*args, **kwargs)
#     return wrapper

def permission_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 检查用户是否登录
        if 'username' not in session:
            flash('请先登录')
            return redirect(url_for('login'))

        # 获取用户的权限
        if not hasattr(g, 'permissions'):
            g.permissions = get_user_permissions(session['username'])

        requested_url = request.path
        if requested_url not in g.permissions:
            return jsonify({'error': 403})

        return f(*args, **kwargs)

    return decorated_function

def get_user_permissions(username):
    mysql = MysqlUtil()
    user = mysql.fetchone("select * from user where Name = %s", (username,))
    if user:
        role_permissions = mysql.fetchalls("""
            SELECT p.Url AS permission_url
            FROM user u
            JOIN user_role ur ON u.USER_id = ur.USER_id
            JOIN role r ON ur.Role_id = r.Role_id
            JOIN role_permission rp ON r.Role_id = rp.Role_id
            JOIN permission p ON rp.Permission_id = p.Permission_id
            WHERE u.USER_id = %s
        """, (user['USER_id'],))
        print(role_permissions)
        return [rp['permission_url'] for rp in role_permissions]
    return []

@app.before_request
def load_user_permissions():
    if 'username' in session:
        g.permissions = get_user_permissions(session['username'])

@app.route('/')
def index():
    return redirect(url_for('shouye'))

# 注册
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['psw']
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
        print(username, password)

        try:
            mysql = MysqlUtil()
            user_id = mysql.insert("INSERT INTO user (Name, Password) VALUES (%s, %s)", (username, hashed_password))
            mysql.insert("INSERT INTO user_role (USER_id, Role_id) VALUES (%s, %s)", (user_id, 2))
            return redirect(url_for('login'))
        except Exception as e:
            print('注册失败:', e)
            return 500

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['psw'].encode('utf-8')
        print(username, password)

        try:
            mysql = MysqlUtil()
            user = mysql.fetchone("select * from user where Name = %s", (username,))
            if user and bcrypt.checkpw(password, user['Password'].encode('utf-8')):
                session['username'] = username
                return redirect(url_for('index'))
            else:
                return render_template('login.html', errno='登录失败')
        except Exception as e:
            print('登录失败:', e)
            return render_template('login.html', errno='服务器错误'), 500

@app.route('/shouye', methods=['GET', 'POST'])
def shouye():
    shouye = {'sy': '欢迎来首页'}
    return render_template('shouye.html', shouye=shouye)

# 客户一
@app.route('/kehu', methods=['GET'])
@permission_required
def kehu():
    kehu = {'huawu': '华为'}
    return render_template('kehu.html', kehu=kehu)

# 客户二
@app.route('/keqq', methods=['GET'])
@permission_required
def keqq():
    xiaomi = {'xiaomi': '小米'}
    return render_template('keqq.html', keqq=xiaomi)

# 编辑
@app.route('/bianji', methods=['GET', 'POST'])
@permission_required
def bianji():
    bianji = {'A': '编辑'}
    return render_template('bianji.html', bianji=bianji)

# 删除
@app.route('/delete', methods=['GET', 'POST'])
@permission_required
def delete():
    delete = {'B': '删除'}
    return render_template('delete.html', delete=delete)



#检查用户名是否存在
@app.route('/checkname', methods=['POST'])
def check_name():
    #print(request.form)
    username = request.form.get('username') #获取字典值
    mysql = MysqlUtil()
    #根据username在数据库中进行查询获取的第一条数据
    data = mysql.fetchone("select * from user where Name = %s", (username,))
    #print(data)
    if data:
        return {'code': 2000, 'msg':'用户名已存在'}
    else:
        return {'code': 2001, 'msg': '用户名不存在'}




#====================






























# 退出登录
@app.route('/logout')
def logout():
    session.clear()
    flash('您已成功退出', 'success')
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)